<template>
  <!-- 财务信息 -->
  <div class="shop-finance-info component-shop-process-finance">
    <!-- 表格上方标题 -->
    <div
      v-if="paySettlementType===0"
      class="table-data-title"
    >
      <div class="text">
        <span class="stress">*</span>{{ $t('shopProcess.add') }}&nbsp;{{ $t('shopProcess.settlementAccount') }}
      </div>
      <div class="tips">
        {{ $t('shopProcess.added') }}
        <span class="txt-bold">{{ bankCartInfoForm.data.length }}</span>
        {{ $t('shopProcess.piece') }}&nbsp;{{ $t('shopProcess.settlementAccount') }}，{{ $t('shopProcess.mostAdd') }}
        <span class="txt-bold">{{ maxNumOfbank }}</span>
        {{ $t('shopProcess.piece') }}&nbsp;{{ $t('shopProcess.settlementAccount') }}，{{ $t('shopProcess.settlementAccountEditTips') }}
      </div>
      <div
        v-if="applyStatus !== 0 && applyStatus !== 1"
        class="edit-btn default-btn primary-btn"
        @click="addBankInfo()"
      >
        {{ $t('shopProcess.add') }}
      </div>
    </div>
    <div
      v-else
      class="table-data-title"
    >
      <div class="text">
        <span class="stress">*</span>{{ $t('allinpay.clearingBankAccount') }}
      </div>
      <div class="tips">
        {{ $t('allinpay.processBindAccNoTip') }}
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-con settlement-accounts-table">
      <!-- 添加图表 -->
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        v-if="applyStatus !== 0 && applyStatus !== 1"
        ref="bankCartInfoFormRef"
        :model="bankCartInfoForm"
        :rules="bankCartInfoForm.rule"

        @submit.prevent
      >
        <el-table
          ref="settlementAccountsTableRef"
          :data="bankCartInfoForm.data"
          header-cell-class-name="table-header"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            :label="$t('number')"
            width="80"
          />
          <template v-if="paySettlementType===0">
            <el-table-column
              prop="bankName"
              :label="$t('shopProcess.bankName')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.bankName'"
                  :rules="bankCartInfoForm.rule.bankName"
                >
                  <el-input
                    v-model="scope.row.bankName"
                    :placeholder="$t('shopProcess.brandNameInputTips')"
                    maxlength="20"
                    @blur="
                      scope.row.bankName =
                        scope.row.bankName ?
                          removeHeadAndTailSpaces(scope.row.bankName) :
                          scope.row.bankName
                    "
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="recipientName"
              :label="$t('shopProcess.recipientName')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.recipientName'"
                  :rules="bankCartInfoForm.rule.recipientName"
                >
                  <el-input
                    v-model="scope.row.recipientName"
                    maxlength="20"
                    :placeholder="$t('shopProcess.recipientNameInputTips')"
                    @blur="
                      scope.row.recipientName =
                        scope.row.recipientName ?
                          removeHeadAndTailSpaces(scope.row.recipientName) :
                          scope.row.recipientName
                    "
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="cardNo"
              :label="$t('shopProcess.account')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.cardNo'"
                  :rules="bankCartInfoForm.rule.cardNo"
                >
                  <el-input
                    v-model="scope.row.cardNo"
                    maxlength="30"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    :placeholder="$t('shopProcess.cardNoInputTips')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="openingBank"
              :label="$t('shopProcess.openingBank')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.openingBank'"
                  :rules="bankCartInfoForm.rule.openingBank"
                >
                  <el-input
                    v-model="scope.row.openingBank"
                    :placeholder="$t('shopProcess.branchInputTips')"
                    maxlength="20"
                    @blur="
                      scope.row.openingBank =
                        scope.row.openingBank ?
                          removeHeadAndTailSpaces(scope.row.openingBank) :
                          scope.row.openingBank
                    "
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="50">
              <template #default="scope">
                <el-icon
                  v-if="bankCartInfoForm.data.length > 1"
                  @click="deleteBankInfoItem(scope.$index)"
                >
                  <Remove />
                </el-icon>
              </template>
            </el-table-column>
          </template>
          <template v-else-if="paySettlementType===1">
            <el-table-column
              prop="parentBankName"
              :label="$t('allinpay.bankName')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.parentBankName'"
                  :rules="bankCartInfoForm.rule.parentBankName"
                >
                  <el-select
                    v-model="selectBank"
                    filterable
                    :placeholder="$t('allinpay.pleaseSelect')"
                    style="width:200px"
                    @change="changeBank"
                  >
                    <el-option
                      v-for="item in bankList"
                      :key="item.bankId"
                      :label="item.bankName"
                      :value="item.bankName"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="bankName"
              :label="$t('allinpay.branchName')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.bankName'"
                  :rules="bankCartInfoForm.rule.bankName"
                >
                  <el-input
                    v-model="scope.row.bankName"
                    maxlength="20"
                    :placeholder="$t('allinpay.forExample') + '南京市雨花区雨花支行'"
                    style="width:200px"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="accountNo"
              :label="$t('allinpay.businessPublicAccounts')"
              width="300"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.accountNo'"
                  :rules="bankCartInfoForm.rule.accountNo"
                >
                  <el-input
                    v-model.trim="scope.row.accountNo"
                    maxlength="19"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    :placeholder="$t('allinpay.pleaseEntePublicAccount')"
                    style="width:230px"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="unionBank"
              :label="$t('allinpay.paymentLineNumber')"
            >
              <template #default="scope">
                <el-form-item
                  :prop="'data.' + scope.$index + '.unionBank'"
                  :rules="bankCartInfoForm.rule.unionBank"
                >
                  <el-input
                    v-model="scope.row.unionBank"
                    :placeholder="$t('allinpay.pleaseEnterDigitLineNumber')"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="12"
                    style="width:230px"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-form>

      <!-- 展示列表 -->
      <div
        v-if="applyStatus === 0 || applyStatus === 1"
        class="show-tab"
      >
        <el-table
          :data="bankCartInfoForm.data"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            :label="$t('number')"
            width="80"
          />
          <template v-if="paySettlementType===0">
            <el-table-column
              prop="bankName"
              :label="$t('shopProcess.bankName')"
            />
            <el-table-column
              prop="recipientName"
              :label="$t('shopProcess.recipientName')"
            />
            <el-table-column
              prop="cardNo"
              :label="$t('shopProcess.cardNo')"
            />
            <el-table-column
              prop="openingBank"
              :label="$t('shopProcess.openingBank')"
            />
          </template>
          <template v-else-if="paySettlementType===1">
            <el-table-column
              prop="parentBankName"
              :label="$t('allinpay.bankName')"
            />
            <el-table-column
              prop="bankName"
              :label="$t('allinpay.branchName')"
            />
            <el-table-column
              prop="accountNo"
              :label="$t('allinpay.businessPublicAccounts')"
            />
            <el-table-column
              prop="unionBank"
              :label="$t('allinpay.paymentLineNumber')"
            />
          </template>
        </el-table>
      </div>

      <!-- 脚部按钮 -->
      <div class="footer">
        <div
          v-if="applyStatus !== 0 && applyStatus !== 1"
          class="btn-row"
        >
          <div
            class="default-btn"
            @click="toPrevStep"
          >
            {{ $t('shopProcess.previousStep') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="saveBankCartInfo"
          >
            {{ $t('shopProcess.submitApply') }}
          </div>
        </div>
        <div
          v-if="applyStatus === 0 || applyStatus === 1"
          class="btn-row"
        >
          <div
            class="default-btn"
            @click="toPrevStep"
          >
            {{ $t('shopProcess.seePreviousStep') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { validNoEmptySpace, removeHeadAndTailSpaces } from '@/utils/validate'
import { ElMessage } from 'element-plus'

defineProps({
  // 申请步骤 4.财务信息
  applyStep: {
    default: 4,
    type: [String, Number]
  },
  // 是否不可以编辑信息, 当申请状态为待审核时不能编辑
  isNotEdit: {
    default: false,
    type: Boolean
  },
  // 店铺申请状态 0：未审核 1：已通过 -1：未通过 -2：未提交过申请
  applyStatus: {
    default: 0,
    type: [String, Number]
  }
})
const emit = defineEmits(['backToFirstStep', 'toPrevStep'])

const allinPayStore = useAllinpayStore()

const paySettlementType = computed(() => {
  return allinPayStore.paySettlementType
})

// 结算账户最大可添加数
const maxNumOfbank = ref(5)

const validEmptyTab = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const bankCartInfoForm = reactive({
  // 添加的结算账户列表
  data: [
    {
      bankName: '',
      recipientName: '',
      cardNo: '',
      openingBank: '',
      accountNo: '', // 企业对公账户
      parentBankName: '', // 开户银行名称
      unionBank: '', // 支付行号 12位数字
      bankCardPro: 1 // 银行卡属性 0法人 1企业对公
    }
  ],
  rule: {
    bankName: [
      { required: true, message: paySettlementType.value === 1 ? $t('allinpay.branchTip') : $t('shopProcess.brandNameNotEmpty'), trigger: 'blur' },
      { min: 2, max: 20, message: paySettlementType.value === 1 ? $t('allinpay.branchTip2') : $t('shopProcess.brandNameErrorTips'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    recipientName: [
      { required: true, message: $t('shopProcess.recipientNameNotEmpty'), trigger: 'blur' },
      { min: 2, max: 20, message: $t('shopProcess.recipientNameInputTips'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    cardNo: [
      { required: true, message: $t('shopProcess.accountNotEmpty'), trigger: 'blur' },
      { min: 8, max: 30, message: $t('shopProcess.bankCardInputTips'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    openingBank: [
      { required: true, message: $t('shopProcess.openingBankNotEmpty'), trigger: 'blur' },
      { min: 2, max: 20, message: $t('shopProcess.openingBankErrorTips'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    accountNo: [
      { required: true, message: $t('allinpay.pleaseEntePublicAccount'), trigger: 'blur' }
    ],
    parentBankName: [
      { required: true, message: $t('allinpay.pleaseEnterBankName'), trigger: 'change' }
    ],
    unionBank: [
      { required: true, message: $t('allinpay.enterLineNumber'), trigger: 'blur' },
      { min: 12, max: 12, message: $t('allinpay.enterLineNumber2'), trigger: 'blur' }
    ]
  }
})

const selectBank = ref('') // 选择的银行，通联

onMounted(() => {
  if (paySettlementType.value === 1) {
    bankCartInfoForm.data = [{
      bankName: '',
      accountNo: '', // 企业对公账户
      parentBankName: '', // 开户银行名称
      unionBank: '', // 支付行号 12位数字
      bankCardPro: 1 // 银行卡属性 0-法人 1-企业对公
    }]
    getBankList()
  } else {
    bankCartInfoForm.data = [{
      bankName: '',
      recipientName: '',
      cardNo: '',
      branchName: ''
    }]
  }
  getBankCartInfo()
})

/**
 * 获取银行卡列表
 */
const getBankCartInfo = () => {
  http({
    url: http.adornUrl('/shop/shopBankCard/getShopBankCardList'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    bankCartInfoForm.data = data
    if (bankCartInfoForm.data === null || bankCartInfoForm.data.length === 0) {
      if (paySettlementType.value === 1) {
        bankCartInfoForm.data = [{
          bankName: '',
          accountNo: '', // 企业对公账户
          parentBankName: '', // 开户银行名称
          unionBank: '', // 支付行号 12位数字
          bankCardPro: 1 // 银行卡属性 0法人 1企业对公
        }]
      } else {
        bankCartInfoForm.data = [
          {
            bankName: '',
            recipientName: '',
            cardNo: '',
            branchName: ''
          }
        ]
      }
    } else if (paySettlementType.value === 1) {
      bankCartInfoForm.data = [{
        ...data[0],
        accountNo: data[0].bankCardNo,
        bankName: data[0].openingBank,
        parentBankName: data[0].bankName
      }]
      selectBank.value = data[0].bankName
    }
  })
}

const bankList = ref([])
// 获取可选银行名称列表（通联）
const getBankList = () => {
  http({
    url: http.adornUrl('/publicBank/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    bankList.value = data
  })
}

const changeBank = (value) => {
  bankCartInfoForm.data[0].parentBankName = value
}

/**
 * 增加银行信息项
 */
const addBankInfo = () => {
  if (bankCartInfoForm.data.length < 5) {
    bankCartInfoForm.data.push(
      {
        bankName: '',
        recipientName: '',
        cardNo: '',
        openingBank: ''
      }
    )
  } else {
    ElMessage({
      message: $t('shopProcess.cardMaxLimitTips'),
      type: 'error',
      duration: 1000
    })
  }
}

/**
 * 删除银行信息项
 * @param {Number} index 索引
 */
const deleteBankInfoItem = (index) => {
  bankCartInfoForm.data.splice(index, 1)
}

const bankCartInfoFormRef = ref(null)
let isSubmit = false
/**
 * 保存银行卡信息
 */
const saveBankCartInfo = () => {
  bankCartInfoFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit) {
        return
      }
      isSubmit = true
      let req
      if (paySettlementType.value === 1) {
        req = http({
          url: http.adornUrl('/shop/shopBankCard/allinpaySaveAndApplyShop'),
          method: 'post',
          data: bankCartInfoForm.data[0]
        })
      } else {
        req = http({
          url: http.adornUrl('/shop/shopBankCard/saveAndApplyShop'),
          method: 'post',
          data: bankCartInfoForm.data
        })
      }
      req.then(() => {
        ElMessage({
          message: $t('shopProcess.submitApplySuccessTips'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            isSubmit = false
            if (paySettlementType.value === 1) {
              location.reload()
              useRouter().push({ path: '/home' })
              return
            }
            // 获取银行卡列表
            getBankCartInfo()
            emit('backToFirstStep')
          }
        })
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

/**
 * 上一步
 */
const toPrevStep = () => {
  emit('toPrevStep')
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
